package threads;

import java.io.*;
import java.net.*;

import sjtu.ChatClient.SystemConstants;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;

public class PlayAudioThread implements Runnable {
	private AudioTrack audioTrack;
	private boolean isStopped = false;
	private int port;
	private DatagramSocket socket;
	
	public PlayAudioThread(int port){
		this.port = port;
		socket = null;
	}
	
	
	private synchronized boolean isStopped(){
		return isStopped;
	}
	
	public synchronized void stop(){
		isStopped = true;
		audioTrack.stop();
		audioTrack.release();
		socket.close();
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		int minSize = AudioTrack.getMinBufferSize(SystemConstants.AUDIO_FREQUENCY, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
		audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, SystemConstants.AUDIO_FREQUENCY, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minSize, AudioTrack.MODE_STREAM);
		audioTrack.play();
		
		try {
			socket = new DatagramSocket(port);
			byte [] buffer = new byte[minSize];
			while(isStopped() == false){
				DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
				socket.receive(packet);
				audioTrack.write(packet.getData(), 0, packet.getLength());
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
